<?php

class Application_Model_NarociloMapper
{

    protected $_dbTable;

    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Narocilo');
        }
        return $this->_dbTable;
    }

    public function save(Application_Model_Narocilo $narocilo, $insert = false)
    {
        $data = array(
            'idnarocilo' => $this->getLastInsertId()+1,
            'kosarica_sifra_kosarice' => $narocilo->getKosarica_sifra_kosarice(),
            'stranka_emso' => $narocilo->getStranka_emso()
        );

        try {
            if (!$insert) {
                $where = array('idnarocilo = ?' => $data['idnarocilo'], 'stranka_emso' => $data['stranka_emso']);
                $this->getDbTable()->update($data, $where);
            } else {
                $this->getDbTable()->insert($data);
            }
        } catch (Exception $e) {
            echo "Error: ".$e->getMessage();
            die;
        }

    }

    public function find($id, Application_Model_Narocilo &$narocilo)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();

        $narocilo->setSifra_kosarice($row->kosarica_sifra_kosarice)
            ->setIdNarocilo($row->idnarocilo)
            ->setStranka_emso($row->stranka_emso);

    }

    public function fetchRow($where) {
        return $this->getDbTable()->fetchRow($where);
    }


    public function fetchAll($where) {
        return $this->getDbTable()->fetchAll($where);
    }

    public function update($idnarocilo, $polje, $vrednost) {
        $where = $this->getDbTable()->getAdapter()->quoteInto('idnarocilo = ?', $idnarocilo);
        $this->getDbTable()->update(array($polje => $vrednost), $where);
    }

    public function getIzdelki($idnarocila = null) {
       
          $where = array('idnarocilo = ?' => $data['idnarocilo']);
          var_dump($this->getDbTable()->fetchRow($data, $where));
          die;
          // za sql funkcije poglej v zend knjiznico -> Zend_Db_Adapter_Abstract
          // $sifra kosarice = $narocilo[sifra]
          // element kosare mapper -> fetchAll($where -> sifra_kosarice = $sifra kosarice)
          // izdelek = new Application_Model_Izdelek -> set vrednosti
          // array[] izdelk
          
    }

    public function getLastInsertId() {
        $row = $this->getDbTable()->getAdapter()->query('SELECT idnarocilo FROM narocilo ORDER BY idnarocilo DESC LIMIT 1')->fetchAll();
        return $row[0]['idnarocilo'];
    }
}

